import asyncio
import os

from WebBackend.utils import mylog


def execute_cmd(cmd='', return_type: str = 'list') -> str | list[str]:
    mylog.info(f' Executing {cmd}')
    out = os.popen(cmd)
    text = out.readlines()
    if return_type == 'str':
        text = "".join(text)
    out.close()
    return text


async def execute_cmd_async(cmd: str = '', return_type: str = 'list') -> str | list[str]:
    proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    stdout, stderr = await proc.communicate()
    if return_type == 'str':
        stdout = "".join(line + '\n' for line in stdout.decode().splitlines())
    return stdout
